﻿using System.Security.Claims;

namespace Audit.EntityFramework.Core.Samples.Infrastructure.CurrentUser;

public static class ClaimsPrincipalExtensions
{
    public static int GetUserId(this ClaimsPrincipal? principal)
    {
        var userId = principal?.FindFirstValue(ClaimTypes.NameIdentifier);

        return int.TryParse(userId, out int parsedUserId) ?
            parsedUserId :
            throw new ApplicationException("User id is unavailable");
    }

    public static string GetUserName(this ClaimsPrincipal? principal)
    {
        var userName = principal?.FindFirstValue(ClaimTypes.Name);

        return !string.IsNullOrEmpty(userName) ?
            userName :
            throw new ApplicationException("User name is unavailable");
    }
}
